package com.easy.activiti;

import com.easy.activiti.ext.IActivitiCoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.stream.Collectors;

/**
 * @author zhouchuang
 * 2024-11-02 13:30:00
 */

@EnableWebSecurity
public class ActivitiWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private IActivitiCoreService activitiCoreService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭csrf防护
                .csrf().disable()
                .headers().frameOptions().disable()
                .and()

                //定制url访问权限
                .authorizeRequests()

                //无需登录即可访问
                .antMatchers("/**").permitAll()
                .and()
        ;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                IActivitiCoreService.AuthConfigServer.User user = activitiCoreService.authConfigServer().username(s);
                return new User(user.getUserName(), passwordEncoder().encode("123456"),
                        user.getRoles().stream().map(role->new SimpleGrantedAuthority(role)).collect(Collectors.toList()));
            }
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
